import request from '@utils/request'
import { APIParams, APIResult } from '@utils/request/type'
import { VideoDTO, VideoSaveForm } from '@/api/entity/video'
import { SceneDTO } from '@/api/entity/scene'
import { ObjectUtil } from '@utils/object-util'
import { ElTreeData } from '@typings/element-plus'
import { ServerEnum } from '@/api/enum/server'

/**
 * 分页查询
 * @param params
 */
export const getVideoListByPageAPI = (params: APIParams.Page<VideoDTO>) =>
  request.post<APIResult.Page<VideoDTO[]>>(ServerEnum.System + '/video/page', params)

/**
 * 根据id获取摄像头
 * @param params
 */
export const getVideoByIdAPI = (params: { id: string }) => request.get<APIResult<VideoDTO>>(ServerEnum.System + '/video/getById/' + params.id)

/**
 * 根据场景id获取摄像头
 * @param params
 */
export const getVideoBySceneIdAPI = (params: { id: string }) => request.get<APIResult<VideoDTO>>(ServerEnum.System + '/video/getByGroup' + params.id)

/**
 * 添加摄像头
 * @param params
 */
export const addVideoAPI = (params: VideoSaveForm) => request.post(ServerEnum.System + '/video/save', params)

/**
 * 编辑摄像头
 * @param params
 */
export const editVideoAPI = (params: VideoSaveForm) => request.post(ServerEnum.System + '/video/update', params)

/**
 * 删除摄像头
 * @param params
 */
export const delVideoAPI = (params: { id: string }) => request.get(ServerEnum.System + '/video/deleteById/' + params.id)

/**
 * 获取场景和摄像头层级列表
 */
export const getVideoBySceneAPI = () => request.get<APIResult<SceneDTO[]>>(ServerEnum.System + '/video/getByGroup')

/**
 * 获取场景和摄像头层级列表 - 格式化树数据
 */
type ElTreeDataType = ElTreeData<{ isVideo: boolean, data: VideoDTO }>
export const getVideoBySceneTreeAPI = async () => {
  const res = await getVideoBySceneAPI()
  const { data, code } = res.data
  if (code === 200 && data.length) {
    const resultData = []
    ObjectUtil.deepForEach<SceneDTO, ElTreeDataType, ElTreeDataType>(data, (item, resolve, parent) => {
      const children = parent?.children || resultData
      const isVideo = !!parent
      const _item = { isVideo, label: item.name, value: item.id } as ElTreeDataType
      if (isVideo) {
        _item.key = 'V' + item.id
        _item.data = item
      } else {
        _item.key = 'S' + item.id
        _item.children = []
        item.videoDTOList && resolve(item.videoDTOList, _item)
      }
      children.push(_item)
    })
    res.data.data = resultData as any
  }
  return res as unknown as APIResult.Response.Data<ElTreeDataType[]>
}
